#include "netset.h"
#include "ui_netset.h"

Netset::Netset(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Netset)
{
    ui->setupUi(this);
    initWindow();
    s_socket = new QTcpServer(this);
    client_socket = new QTcpSocket(this);
    udp_socket = new QUdpSocket(this);
}

Netset::~Netset()
{
    delete ui;
}

void Netset::initWindow()
{
    QString name = QHostInfo::localHostName();
    QHostInfo hinfo= QHostInfo::fromName(name);
    QList<QHostAddress> addrs = hinfo.addresses();
    for(auto  addr : addrs)
    {
        if(addr.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ui->ipComboBox->addItem(addr.toString());
        }
    }
}





void Netset::on_conButton_clicked()
{
#if 1//udp接收，发送时候不需要bind
    /* udp*/
    udp_socket->bind(QHostAddress(ui->ipComboBox->currentText()),
                     ui->portLineEdit->text().toShort());
    connect(udp_socket,&QUdpSocket::readyRead,[=](){
        QByteArray arr;
        int size = udp_socket->pendingDatagramSize();
        arr.resize(size);
        QHostAddress addr;
        quint16 port;
        udp_socket->readDatagram(arr.data(),size,&addr,&port);
        ui->textEdit->append(arr);
    });
#endif

#if 0//TCP：本地充当客户端
    /*
     *客户端
     */
    //连接远程主机
    client_socket->connectToHost(QHostAddress(ui->ipComboBox->currentText()),
                                 ui->portLineEdit->text().toShort());

    connect(client_socket,&QTcpSocket::connected,[=](){
        ui->textEdit->append("连接已经建立");
    });
#endif
#if 0//TCP充当服务器
    /*
     * 服务器
     */
    if(ui->conButton->text() == "连接")
    {
        bool isListen = s_socket->listen(QHostAddress(ui->ipComboBox->currentText()),
                                         ui->portLineEdit->text().toShort());
        if(isListen)
        {
            ui->textEdit->append("监听成功");
            ui->conButton->setText("关闭");
            connect(s_socket,&QTcpServer::newConnection,[=](){
                //获取通信套接字
                c_socket = s_socket->nextPendingConnection();
                connect(c_socket,&QTcpSocket::readyRead,[=](){
                    ui->textEdit->append( c_socket->readAll());
                });
            });
        }
        else{
            ui->textEdit->append("监听失败");
        }
    }
    else if(ui->conButton->text() == "关闭")
    {
        //关闭监听
        s_socket->close();
        ui->conButton->setText("连接");
        ui->textEdit->append("监听关闭");
    }
#endif
}

void Netset::on_sendButton_clicked()
{
#if 1//udp的发送
    udp_socket->writeDatagram(ui->sendEdit->toPlainText().toUtf8(),
                              QHostAddress("127.0.0.1"),10001);
#endif


#if 0/* TCP:本地充当客户端时候的发送*/
    client_socket->write(ui->sendEdit->toPlainText().toUtf8());
#endif
}
